<template>
   <div>
      <section class="loginContainer">
         <div class="loginInner">
            <!-- 选择登录类型 -->
            <div class="login_header">
               <h2 class="login_logo">早点外卖</h2>
               <div class="login_header_title">
                  <a
                     href="javascript:;"
                     :class="{ on: login }"
                     @click="changeLoginType(true)"
                     >登录用户</a
                  >
                  <a
                     href="javascript:;"
                     @click="changeLoginType(false)"
                     :class="{ on: !login }"
                     >注册用户</a
                  >
               </div>
            </div>
            <div class="login_content">
               <form @submit.prevent="callback(login?doLogin:doRegister)">
                  <!-- 注册用户 -->
                  <div :class="{ on: !login }">
                     <section class="login_message">
                        <input
                           type="text"
                           pattern="^\w{3,10}"
                           placeholder="输入用户名"
                           v-model="registerInfo.username"
                        />
                     </section>
                     <section class="login_verification">
                        <input
                           type="password" 
                           pattern="[0-9a-zA-Z_]{3,11}"
                           placeholder="请输入密码"
                           v-model="registerInfo.pass1"
                        />
                     </section>
                     <section class="login_verification">
                        <input
                           type="password"
                           pattern="[0-9a-zA-Z_]{3,11}"
                           placeholder="再输入密码"
                           v-model="registerInfo.pass"
                        />
                     </section>
                     <section class="login_hint">
                        密码由3~11位数字字母下划线组成
                     </section>
                  </div>
                  <!-- 登录用户 -->
                  <div :class="{ on: login }">
                     <section>
                        <section class="login_message">
                           <input
                              type="text"
                              pattern="^\w{3,10}"
                              placeholder="用户名"
                              v-model="loginInfo.username"
                           />
                        </section>
                        <section class="login_verification">
                           <input
                              :type="passInpType"
                              pattern="[0-9a-zA-Z_]{3,11}"
                              placeholder="密码"
                              v-model="loginInfo.pass"
                           />
                           <div
                              class="switch_button"
                              :class="{ on: showPassword, off: !showPassword }"
                              @click="changeShowPassword"
                           >
                              <div class="switch_circle"></div>
                           </div>
                        </section>
                     </section>
                  </div>
                  <button class="login_submit" type="submit" v-if="login">登录</button>
                  <button class="login_submit" type="submit" v-if="!login">注册</button>
               </form>
               <a href="javascript:;" class="about_us">关于我们</a>
            </div>
         </div>
         <!-- 错误弹窗提示 -->
         <AlertTip 
            :alertText="alertText"
            v-if="alertShow"
            @closeTip="closeTip"
         />
      </section>
   </div>
</template>

<script>
// 子组件
import AlertTip from '@/components/AlertTip/AlertTip'
// API接口
import { toLogin, registerUser, userCookieLogin, saveBaseUserInfo } from "@/api/ajax";
// cookie
import {setCookie} from '@/utils/tools'
// vuex
import { mapMutations } from "vuex";
// vant
import { Toast } from 'mint-ui';

export default {
   name: "Login",
   data() {
      return {
         login: true, // 去登录
         showPassword: false, // 默认不显示密码
         passInpType: "password", // 密码输入框的输入类型
         loginInfo: {
            username: "", // 用户名
            pass: "", // 密码
         },
         registerInfo: {
            username: '', // 注册的用户名
            pass1: '', // 第一次输入的密码
            pass: '', // 第二次输入的密码
         },
         alertShow: false, // 默认不显示弹窗
         alertText: '', // 弹窗显示文本
      };
   },
   components: {
      AlertTip
   },
   methods: {
      ...mapMutations("profile", ["SAVA_USERINNFO"]),
      /* 切换登录类型 */
      changeLoginType(type) {
         this.login = type;
      },
      /* 切换密码的显示状态 */
      changeShowPassword() {
         this.showPassword = !this.showPassword;
      },
      /* 登录 */
      async doLogin() {
         // 非空验证
         if (!this.loginInfo.username && !this.loginInfo.pass) {
            this.myAlertBox('请完整输入用户名密码')
            return
         }
         const { data, code } = await toLogin({
            username: this.loginInfo.username,
            pass: this.loginInfo.pass
         });

         if (!code) {
            this.myAlertBox('用户名密码错误')
            return
         }

         // 存储用户信息
         this.SAVA_USERINNFO(data);
         // 跳转到我的页面
         Toast('登录成功')
         // 存储cookie
         setCookie('username', data.username)
         setTimeout(() => {
            this.$router.replace("/profile");
         }, 200)
      },
      /* 注册 */
      async doRegister() {
         // 非空验证
         for (let key in this.registerInfo) {
            if (!this.registerInfo[key]) return this.myAlertBox('请完善所有必填信息')
         }
         // 用户名是否占用检测
         let { msg:msg1 } = await userCookieLogin(this.registerInfo.username)
         if (msg1 === 'ok') {
            this.myAlertBox('该用户名已被占用')
            return
         }
         if (this.registerInfo.pass1 !== this.registerInfo.pass) {
            this.myAlertBox('请确保两次输入的密码完全一致')
            return
         }
         // 执行注册操作
         const { username, pass } = this.registerInfo
         let { msg:msg2, username: uname, u_id } = await registerUser({ username, pass })
         if (msg2 === 'ok') {
            // 存储基础用户信息到数据库
            const obj = {u_id, pic: 'default.webp'}
            saveBaseUserInfo(obj)
            // 将数据存储到 store 中
            this.SAVA_USERINNFO({ username: uname, pic: 'default.webp', u_id })
            Toast('注册成功')
            // 存储用户cookie
            setCookie('username', username)
            setTimeout(() => {
               this.$router.push('/profile')
            }, 300);
         } else {
            Toast('注册失败')
         }
      },
      /* 表单提交执行的回调函数 */
      callback(cb) {
         cb()
      },
      /* 弹窗提示 */
      myAlertBox(msg) {
         this.alertText = msg
         this.alertShow = true
      },
      /* 关闭弹窗 */
      closeTip() {
         this.alertShow = false
      }
   },
   watch: {
      /* 切换密码输入框 type 类型切换 */
      showPassword(nval) {
         this.passInpType = nval ? "text" : "password";
      },
   },
};
</script>

<style scoped lang="stylus">
.login_content {
   .switch_button.on {
      div {
         left: auto !important;
         right: 0;
      }
   }
}
.login_header {
   background: #fff;
}

.loginContainer {
   width: 100%;
   height: 100vh;
   background: #fff;

   .loginInner {
      padding-top: 60px;
      width: 80%;
      margin: 0 auto;

      .login_header {
         .login_logo {
            font-size: 40px;
            font-weight: bold;
            color: var(--theme);
            text-align: center;
         }

         .login_header_title {
            padding-top: 40px;
            text-align: center;

            >a {
               color: #333;
               font-size: 14px;
               padding-bottom: 4px;

               &:first-child {
                  margin-right: 40px;
               }

               &.on {
                  color: var(--theme);
                  font-weight: 700;
                  border-bottom: 2px solid var(--theme);
               }
            }
         }
      }

      .login_content {
         >form {
            >div {
               display: none;

               &.on {
                  display: block;
               }

               input {
                  width: 100%;
                  height: 100%;
                  padding-left: 10px;
                  box-sizing: border-box;
                  border: 1px solid #ddd;
                  border-radius: 4px;
                  outline: 0;
                  font: 400 14px Arial;

                  &:focus {
                     border: 1px solid var(--theme);
                  }
               }

               .login_message {
                  position: relative;
                  margin-top: 16px;
                  height: 48px;
                  font-size: 14px;
                  background: #fff;

                  .get_verification {
                     position: absolute;
                     top: 50%;
                     right: 10px;
                     transform: translateY(-50%);
                     border: 0;
                     color: #ccc;
                     font-size: 14px;
                     background: transparent;
                  }
               }

               .login_verification {
                  position: relative;
                  margin-top: 16px;
                  height: 48px;
                  font-size: 14px;
                  background: #fff;

                  .switch_button {
                     font-size: 12px;
                     border: 1px solid #ddd;
                     border-radius: 8px;
                     transition: background-color 0.3s, border-color 0.3s;
                     padding: 0 6px;
                     width: 30px;
                     height: 16px;
                     line-height: 16px;
                     color: #fff;
                     position: absolute;
                     top: 50%;
                     right: 10px;
                     transform: translateY(-50%);

                     &.off {
                        background: #fff;

                        .switch_text {
                           float: right;
                           color: #ddd;
                        }
                     }

                     &.on {
                        background: var(--theme);
                     }

                     >.switch_circle {
                        position: absolute;
                        top: -1px;
                        left: -1px;
                        width: 16px;
                        height: 16px;
                        border: 1px solid #ddd;
                        border-radius: 50%;
                        background: #fff;
                        box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
                        transition: transform 0.3s;
                     }
                  }
               }

               .login_hint {
                  margin-top: 12px;
                  color: #999;
                  font-size: 14px;
                  line-height: 20px;

                  >a {
                     color: #02a774;
                  }
               }
            }

            .login_submit {
               display: block;
               width: 100%;
               height: 42px;
               margin-top: 30px;
               border-radius: 4px;
               background: var(--theme);
               color: #fff;
               text-align: center;
               font-size: 16px;
               line-height: 42px;
               border: 0;
            }
         }

         .about_us {
            display: block;
            font-size: 12px;
            margin-top: 20px;
            text-align: center;
            color: #999;
         }
      }

      .go_back {
         position: absolute;
         top: 5px;
         left: 5px;
         width: 30px;
         height: 30px;

         >.iconfont {
            font-size: 20px;
            color: #999;
         }
      }
   }
}
</style>